package com.controller;

import com.google.protobuf.Internal;
import com.pojo.SysUser;
import com.service.SysUserService;
import com.sun.org.apache.xalan.internal.xsltc.runtime.Constants;
import jakarta.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private static Logger logger=Logger.getLogger(SysUserController.class);
    @Resource
    private SysUserService sysUserService;

    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/login")
    public String doLogin(Model model, HttpSession session, String account, String password){
       SysUser sysUser= sysUserService.login(account,password);
        if(sysUser==null){
            //登录失败
            model.addAttribute("error","账号或密码错误!");
            return "login";
        }

        //登陆成功
        session.setAttribute("USER_SESSION",sysUser);
        return "frame";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        //移除当前登录的账号信息
        session.removeAttribute("USER_SESSION");
        // 销毁Session会话
        session.invalidate();
        return "redirect:/user/login";
    }
    /**
     * 捕获异常信息，设置到作用域，跳转到统一异常处理画面
//     * @param e
//     * @param request
     * @return
     */
//    @ExceptionHandler
//    public String handlerException(RuntimeException e, HttpServletRequest request){
//        request.setAttribute("error",e.getMessage());
//        return "login";
//    }
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "sysUser/add";
    }
//    @RequestMapping("/add")
//    public String add(SysUser sysUser,HttpSession session){
//        sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION).getId()));
//        if(sysUserService.add(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/add";
//    }
    @RequestMapping("/view/{id}")
    public String view(@PathVariable String id,Model model){
        logger.debug("根据id查询用户详情"+id);
        SysUser sysUser=sysUserService.getUserById(id);
        model.addAttribute(sysUser);
        return "sysUser/view";
    }
    @RequestMapping("/toUpdate")
    public String toUpdate(@RequestParam String id,String uid,Model model){
        logger.debug("跳转到修好用户信息页面");
        SysUser sysUser=sysUserService.getUserById(uid);
        model.addAttribute(sysUser);
        return "sysUser/update";
    }
//    @RequestMapping("/update")
//    public String update(SysUser sysUser,HttpSession session){
//        logger.debug("修改用户信息");
//        sysUser.setUpdatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION).getId()));
//        if(sysUserService.update(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/update";
//    }
    @RequestMapping("/add")
    public String toAdd(@ModelAttribute("sysUser") SysUser sysUser){
        return "sysUser/add";
    }
//    @RequestMapping("/add")
//    public String add(SysUser sysUser,HttpSession session){
//        sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION).getId()));
//        if(sysUserService.add(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/add";
//    }
//    @RequestMapping("/add")
//    public String add(@Valid SysUser sysUser, BindingResult bindingResult, HttpSession session) {
//        if (bindingResult.hasErrors()) {
//            logger.debug("添加用户验证失败");
//            return "sysUser/add";
//        }
//        sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION).getId()));
//        if (sysUserService.add(sysUser)) {
//            return "redirect:/user/list";
//        }
//        return "sysUser/add";
//    }
//    @RequestMapping("/add")
//    public String add(SysUser sysUser, HttpSession session, HttpServletRequest request,
//                      @RequestParam(value ="idPic",required = false)MultipartFile idPic){
//        String idPicPath=null;
//        if(!idPic.isEmpty()){
//            String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
//            logger.info("上传文件路径:"+path);
//            String originalFile=idPic.getOriginalFilename();
//            logger.info("原文件名为:"+originalFile);
//            String prefix= FilenameUtils.getExtension(originalFile);
//            logger.debug("原文件后缀:"+prefix);
//            int filesize=500000;
//            logger.debug("文件大小"+idPic.getSize());
//            if(idPic.getSize()>filesize){
//                request.setAttribute("uploadFileError","*上传大小不得超过500KB");
//                return "sysUser/add";
//            }else if(prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")
//            ||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("pneg")){
//                String fileName=System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_Personal."+prefix;
//                logger.debug("新文件的文件名称为:"+fileName);
//                File targetFile=new File(path);
//                if(!targetFile.exists()){
//                    targetFile.mkdirs();
//                }
//                try {
//                    idPic.transferTo(new File(targetFile,fileName));
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    request.setAttribute("uploadFileError","上传失败");
//                    return "sysUser/add";
//                }
//                idPicPath=File.separator+"statics"+File.separator+"uploadfiles"+File.separator+fileName;
//            }else {
//                request.setAttribute("uploadFileError","上传图片格式不正确");
//                return "sysUser/add";
//            }
//        }
//        sysUser.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION).getId()));
//        sysUser.setIdPic(idPicPath);
//        if(sysUserService.add(sysUser)){
//            return "redirect:/user/list";
//        }
//        return "sysUser/add";
//    }

}
